<template>
  <div class="clientType">
    <div class="title-container">
      <div class="left-box">
        <el-form ref="form" :model="searchForm" :inline="true" class="formClass">
          <el-form-item>
            <el-input
              prefix-icon="el-icon-search"
              type="input"
              placeholder="请输入公司名称"
              v-model="searchForm.companyName"
              style="margin-right: 10px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <global-card>
      <template #leftTitle>
        <perButton label="新建" type="primary" icon="el-icon-plus" perms="PROTOCOL_ADD"
                   @click="newCompanyClick"></perButton>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </template>
      <template #content>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          class="elTable"
        >
          <el-table-column type="index" label="序号" width="80" align="center"/>
          <el-table-column prop="companyName" label="投资照片" align="center" width="120">
            <template #default="{ row }">
              <viewer class="w-100 h-100">
                <img
                  style="display: inline-block;height: 80px;width: 80px;"
                  :src="row.headUrl1.split('&')[0]"
                  class="mt-1 mr-1 ml-1 mb-1 bg-light h-100 w-100 obj-contain">
              </viewer>
            </template>
          </el-table-column>
          <el-table-column prop="productCode" label="投资编码" align="center" width="100"/>
          <el-table-column prop="productName" label="投资名称" align="center" width="150"/>
          <el-table-column prop="productDesc" label="投资描述" align="center"/>
          <el-table-column prop="companyType" label="是否上架" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.investmentUp == 0 ? "上架" : "下架"}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="{ row }">
              <perButton label="编辑" type="warning" size="mini" perms="PROTOCOL_EDIT"
                         @click="handlerEdit(row)"></perButton>
              <perButton label="删除" type="danger" size="mini" perms="PROTOCOL_DEL"
                         @click="handlerDelete(row)"></perButton>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <pagination
          class="pagination"
          :total="count"
          :page.sync="pageIndex"
          :limit.sync="pageSize"
          @pagination="pagination"
        />
      </template>
    </global-card>

    <!-- 新增编辑 -->
    <yc-dialog
      ref="ycDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="newCompanyModel"
            :rules="rules"
            ref="agreementModelRef"
            label-width="110px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="投资名称" prop="productName">
                  <el-input v-model="newCompanyModel.productName"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="投资描述" prop="productDesc">
                  <el-input v-model="newCompanyModel.productDesc"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否上架" prop="investmentUp">
                  <el-select v-model="newCompanyModel.investmentUp">
                    <el-option
                      v-for="item in userData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="投资类型" prop="hotInvestmentType">
                  <el-radio-group v-model="newCompanyModel.hotInvestmentType">
                    <el-radio :label="0">用户热门投资</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="投资照片" prop=" headUrl1">
                  <div :class="detailsDisabled ? 'editor-container' : ''">
                    <dropzone
                      id="myVueDropzone"
                      v-model="newCompanyModel. headUrl1"
                      :url="$uploadUrl + upload"
                      :thumbnailHeight="100"
                      :thumbnailWidth="100"
                      :defaultImg="imgList"
                      :acceptedFiles="'image/jpeg,image/png'"
                      @dropzone-removedFile="dropzoneR"
                      @dropzone-success="dropzoneS"/>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="xqxx">详情页信息</div>
            <el-upload
              :action="$uploadUrl + upload"
              class="avatar-uploader-quill"
              style="display: none;"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleLogoSuccess2"
            >
            </el-upload>
            <quill-editor v-model="newCompanyModel.investmentRichText"
                          :options="editorOption"
                          class="ql-editor"
                          ref="myQuillEditor"
            ></quill-editor>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import { quillEditor, Quill } from "vue-quill-editor"
  import ImageResize from "quill-image-resize-module" //调整图片大小
  Quill.register("modules/imageResize", ImageResize)
  import "quill/dist/quill.core.css"
  import "quill/dist/quill.snow.css"
  import "quill/dist/quill.bubble.css"

  import Dropzone from "@/components/Dropzone"
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPageProduct,
    insertInvestment,
    updateInvestment,
    deleteProduct
  } from "@/api/investmentPromotionManagement/index"
  import { getToken } from "@/utils/auth"

  export default {
    components: {
      Dropzone,
      quillEditor,
      ycDialog,
      perButton
    },
    data() {
      return {
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        count: 0,
        searchForm: {
          agreementName: "",
          agreementType: ""
        },

        detailsDisabled: false,
        isGlobalMessageShow: false,

        dialogCenterTitle: "",
        dialogTitle: "",
        message: "",

        loading: false,
        newCompanyModel: {
          id: "",
          productName: "",
          productDesc: "",
          investmentUp: "",
          hotInvestmentType: "",
          headUrl1: "",
          investmentRichText: ""
        },
        rules: {
          productName: [
            { required: true, message: "请输入投资名称", trigger: "blur" }
          ],
          productDesc: [
            { required: true, message: "请输入投资描述", trigger: "blur" }
          ],
          investmentUp: [
            { required: true, message: "请选择是否上架", trigger: "change" }
          ],
          hotInvestmentType: [
            { required: true, message: "请选择投资类型", trigger: "change" }
          ],
          headUrl1: [
            { required: true, message: "请选择投资照片", trigger: "change" }
          ]
        },
        headers: {
          token: getToken()
        },
        upload: "/uploadManager/upload",
        videoFlag: false,
        //是否显示进度条
        videoUploadPercent: "",
        //进度条的进度，
        isShowUploadVideo: false,
        //显示上传按钮
        videoForm: {
          showVideoPath: ""  //回显的变量
        },
        userData: [
          { id: 0, name: "上架" },
          { id: 1, name: "下架" }
        ],
        imgList: [],


        maintenanceRecordData: [],
        pageIndex2: 1,
        pageSize2: 20,
        count2: 0,

        editorOption: {
          placeholder: "",
          quill: "",
          modules: {
            imageResize: { // 调整图片大小配置
              displayStyles: {
                backgroundColor: "black",
                border: "none", // 是否加边框
                color: "white" // 拖拽时，图片右下角尺寸文字颜色
              },
              modules: ["Resize", "DisplaySize", "Toolbar"] // 工具包：允许拖拽、显示尺寸、对齐方式
            },
            toolbar:{
              container:[ // 工具栏配置
                ["bold", "italic", "underline", "strike"],          //加粗，斜体，下划线，删除线
                [{ "size": ["small", false, "large", "huge"] }],    // 字体大小
                [{ "header": [1, 2, 3, 4, 5, 6, false] }],          //几级标题
                [{ "color": [] }, { "background": [] }],            // 字体颜色，字体背景颜色
                [{ "align": [] }],                                  //对齐方式
                [{ "indent": "-1" }, { "indent": "+1" }],           // 缩进
                [{ "list": "ordered" }, { "list": "bullet" }],      //列表
                [{ "script": "sub" }, { "script": "super" }],       // 上下标
                ["blockquote", "code-block"],                       //引用，代码块
                ["clean"],                                          //清除字体样式
                ["image", "video"]                                  //上传图片、上传视频
              ],
              handlers: {
                image: (value) => {
                  if (value) {
                    // 调用element的图片上传组件
                    document.querySelector(".avatar-uploader-quill input").click();
                  } else {
                    this.quill.format("image", false);
                  }
                },
              },
            },
          }
        },
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getData()
    },
    methods: {
      async searchClick() {
        await this.getData()
      },
      async getData() {
        const { agreementName, agreementType } = this.searchForm
        this.loading = true
        const data = await queryPageProduct({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          investmentType: 1
        })
        this.tableData = data.object.data
        this.count = data.object.count
        this.loading = false
      },
      pagination(pageItem) {
        this.getData(pageItem.page, pageItem.limit)
      },


      handlerDelete({ id }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { status } = await deleteProduct({
            id
          })
          if (status == 200) {
            this.getData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      // 新建
      newCompanyClick() {
        this.dialogCenterTitle = "新建"
        this.dialogTitle = "新建"

        Object.keys(this.newCompanyModel).forEach((item) => {
          this.newCompanyModel[item] = ""
        })
        this.newCompanyModel.hotInvestmentType = 0
        this.imgList = []

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
      },
      handlerEdit(row) {
        this.dialogCenterTitle = "编辑"
        this.dialogTitle = "编辑"

        this.newCompanyModel = {
          id: row.id,
          productName: row.productName,
          productDesc: row.productDesc,
          investmentUp: row.investmentUp,
          hotInvestmentType: row.hotInvestmentType,
          headUrl1: row.headUrl1,
          investmentRichText: row.investmentRichText,
        }
        if (row.headUrl1) {
          this.imgList = row.headUrl1.split("&")
        }


        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
      },

      dropzoneS(file) {
        const res = JSON.parse(file.xhr.response)
        this.imgList.push(res.object.url)
        this.newCompanyModel.headUrl1 = this.imgList.join("&")
      },
      dropzoneR(file) {
        let res
        let index
        if (file.xhr) {
          res = JSON.parse(file.xhr.response)
          index = this.imgList.findIndex(item => item == res.object.url)
        } else {
          res = file.url
          index = this.imgList.findIndex(item => item == res)
        }
        this.imgList.splice(index, 1)
        this.newCompanyModel.headUrl1 = this.imgList.join("&")
      },

      handleLogoSuccess2(id, file) {
        let quill = this.$refs.myQuillEditor.quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", file.response.object.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      },

      async dialogSave() {
        this.$refs.agreementModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.newCompanyModel.id) {
              // 编辑
              const { status, message } = await updateInvestment({
                ...this.newCompanyModel
              })
              if (status == 200) {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const { status, message } = await insertInvestment({ ...this.newCompanyModel })
              if (status == "200") {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      receive() {
        this.isGlobalMessageShow = false
      },

      refresh() {
        this.searchForm = {
          agreementName: "",
          agreementType: ""
        }
        this.getData()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clientType {
    .title-container {
      display: flex;
      justify-content: flex-end;
      margin-right: 20px;

      .left-box {
        display: flex;

        .formClass {
          /*display: flex;*/
          /*margin-right: 20px;*/

          .el-form-item {
            margin-top: 20px;
            margin-bottom: 0;

            .el-input {
              width: 216px;
            }

            .el-select {
              width: 171px;
              margin-left: 10px;
            }

            .el-date-editor {
              width: 336px;
              margin-left: 10px;
            }
          }
        }

        /*.el-button {*/
        /*  // width: 42px;*/
        /*  height: 36px;*/
        /*  margin-top: 20px;*/
        /*}*/
      }
    }
  }

  .editor-container {
    pointer-events: none;
    background-color: #C0C4CC !important;
    color: #C0C4CC !important;
  }

  .xqxx {
    font-family: Source Han Sans CN;
    font-size: 15px;
    font-weight: 600;
    line-height: 21px;
    padding-left: 15px;
    margin-bottom: -12px;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    /* cursor: no-drop; */
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .drop {
    cursor: no-drop;
  }
</style>
